<template>
  <div class="alarm-container">
    <div class="left">
      <div class="title">报警监控</div>
      <div class="ball-container">
        <WaterBall :value="memAndRom.memValue" :alarm="memAndRom.memWarning" title="内存使用百分比"></WaterBall>
        <WaterBall :value="memAndRom.romValue" :alarm="memAndRom.romWarning" title="硬盘使用百分比"></WaterBall>
      </div>
    </div>
    <div class="right flex-center">
      <div class="living-container">
        <Signal v-if="signal.is4G" :value="signal.signalValue"/>
        <div class="living">
          <div class="status" :class="{'off': detailInfo.onLineStatus !== 'ONLINE'}"></div>
          {{detailInfo.onLineStatus === 'ONLINE' ? '在线':'离线'}}
        </div>
        <div class="type">
          <span>{{ detailInfo.wanCfg || '--' }}</span>
        </div>
      </div>
      <div class="flex-center operator-container">
        <div class="gateway">
          <img src="../../../../statics/img/gateway.png" alt="" style="height: 80%">
        </div>
        <div class="flex-between operator">
          <q-btn class="btn left-btn" unelevated  color="primary" label="重启设备" @click="restartBox" :loading="restartSubmitting"/>
          <q-btn class="btn" unelevated  color="primary" label="专业设置" disable/>
        </div>
        <div class="flex-between operator">
          <q-btn class="btn left-btn" unelevated  color="primary" :disable="lanDisabled" label="LAN1设置" @click="setLan('1')"/>
          <q-btn class="btn" unelevated  color="primary" label="LAN2设置" @click="setLan('2')"/>
        </div>
        <div class="flex-between operator">
          <q-btn class="btn left-btn" unelevated @click="applicationUpgrade"  color="primary" label="应用升级" :loading="submitting"/>
          <q-btn class="btn" unelevated  color="negative" label="恢复出厂值" @click="show = true;gatewayId=''" :loading="resetSubmitting"/>
        </div>
        <div class="operator flex-start">
          <q-btn class="btn left-btn" unelevated  color="negative" @click="testDialog = true" label="测试"/>
        </div>
      </div>
    </div>
    <LanConfig :lanInfo="lanInfo" :visible="lanVisible" @close="closeLanInfo" :lanType="lanType" :boxId="boxId" @updateLanSuccess="updateLanSuccess"/>

    <q-dialog class="add-edit-station-dialog dialog" v-model="show">
      <q-card v-drag style="min-width: 330px;">
        <!-- dialog title -->
        <q-card-section class="dialog-title bg-primary">
          <div class="text-center text-white">恢复出厂值</div>
        </q-card-section>
        <div class="flex-center margin-t-20">
          确认要恢复出厂设置吗？再次确认网关序列号
        </div>
        <q-form @submit="submitReset" class="q-gutter-md dialog-content">
          <q-card-section>
            <q-input v-model="gatewayId" autofocus outlined dense style="width: 266px;"
                     :rules="[val => val && val.length > 0 || '请填写网关序列号']">
              <template v-slot:before>
                <label class="text-right name" style="width: 100px;"><span class="text-red">*</span> 网关序列号:</label>
              </template>
            </q-input>
          </q-card-section>
          <q-separator />
          <q-card-actions align="center" class="dialog-footer text-center margin-t-10">
            <q-btn outline color="primary" label="取消" @click="show = false" class="q-mr-md"/>
            <q-btn unelevated color="primary" label="确认" type="submit"/>
          </q-card-actions>
        </q-form>
      </q-card>
    </q-dialog>

    <q-dialog class="add-edit-station-dialog dialog" v-model="testDialog">
      <q-card v-drag style="min-width: 560px;">
        <!-- dialog title -->
        <q-card-section class="dialog-title bg-primary">
          <div class="text-center text-white">测试</div>
          <q-btn
            style="font-size: 18px;color: white"
            flat round dense
            class="iconfont icontubiao-67 close-btn dialog"
            @click="testDialog = false"
          >
          </q-btn>
        </q-card-section>
        <div style="margin: 20px">
          <div class="flex-between margin-b-20">
            <q-select v-model="testValue"
                      :options="testOption"
                      dense
                      options-dense
                      emit-value
                      map-options
                      outlined
                      style="width: 180px"
            >
              <template v-slot:no-option>
                <div class="no-option" />
              </template>
            </q-select>
            <q-btn class="btn left-btn" unelevated  color="primary" @click="getShadow" label="物理模型"/>
          </div>
          <q-scroll-area class="testArea" ref="scrollTargetRef" :thumb-style="thumbStyle">
            <JsonViewer :json="testResult"></JsonViewer>
          </q-scroll-area>
        </div>
      </q-card>
    </q-dialog>
  </div>
</template>

<script>
import Signal from '../list-components/signal'
import WaterBall from './water-ball'
import {
  appUpdate,
  appVersionCompare,
  getShadow,
  resetBox,
  restartBox
} from '../../../../boot/miot/details'
import LanConfig from './lan-config'
import JsonViewer from 'src/components/json-viewer'
import { mapGetters } from 'vuex'

export default {
  name: 'alarm-monitoring',
  components: {
    Signal,
    WaterBall,
    LanConfig,
    JsonViewer
  },
  data () {
    return {
      thumbStyle: this.CommonConfig.thumbStyle,
      lanVisible: false,
      lanType: '1',
      show: false,
      gatewayId: '',
      submitting: false,
      resetSubmitting: false,
      restartSubmitting: false,
      testDialog: false,
      testValue: '1',
      testOption: [
        { label: '网关ID', value: '1' }
      ],
      testResult: []
    }
  },
  props: {
    boxId: {
      type: String,
      default: ''
    },

    lanInfo: {
      type: Object,
      default: () => {}
    },
    detailInfo: {
      type: Object,
      default: () => {}
    },
    subDevices: {
      type: Array,
      default: () => []
    },
    memAndRom: {
      type: Object,
      default: () => ({
        memValue: 0,
        romValue: 0,
        memWarning: false,
        romWarning: false
      })
    },
    signal: {
      type: Object,
      default: () => ({
        is4G: false,
        signal: 0
      })
    }
  },
  watch: {
    subDevices: {
      immediate: true,
      handler: function (val) {
        if (val && val.length > 0) {
          const option = [{ label: '网关ID', value: '1' }]
          val.forEach(item => {
            option.push({
              label: `${item.deviceName}(${item.assetNumber})`,
              value: item.assetNumber
            })
          })
          this.testOption = option
        }
      }
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ]),
    lanDisabled () {
      return this.detailInfo.wanCfg === 'LAN'
    }
  },
  methods: {
    async submitReset () {
      if (!this.boxId) return
      const gateWayId = this.boxId.split('_')
      if ((gateWayId && this.gatewayId.trim() === gateWayId[1]) || this.boxId === this.gatewayId.trim()) {
        this.resetSubmitting = true

        try {
          await resetBox(this.boxId)
          this.$emit('checkDevice')
        } catch (e) {
          console.log(e)
        } finally {
          this.resetSubmitting = false
          this.show = false
        }
      } else {
        this.$message.error('您输入的网关ID不正确')
      }
    },

    restartBox () {
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>
          确定要重启设备吗？</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      }).onOk(() => {
        // FIXME 调试重启接口
        this.restartBoxConfirm()
      })
    },

    async restartBoxConfirm () {
      if (!this.boxId) return
      this.restartSubmitting = true
      try {
        await restartBox(this.boxId)
        this.$emit('checkDevice')
      } catch (e) {
        console.log(e)
      } finally {
        this.restartSubmitting = false
      }
    },

    setLan (val) {
      this.lanType = val
      this.lanVisible = true
    },

    updateLanSuccess () {
      this.lanVisible = false
      this.$emit('updateLanSuccess')
    },

    applicationUpgrade () {
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>
          确定要应用升级吗？</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      }).onOk(() => {
        this.applicationUpgradeConfirm()
      })
    },

    async applicationUpgradeConfirm () {
      this.submitting = true

      const params = {
        boxId: this.boxId,
        productName: this.detailInfo.productName,
        softWare: this.detailInfo.software,
        type: 'App'
      }

      try {
        const data = await appVersionCompare(params)
        this.$emit('checkDevice')
        if (data.data && data.data.updateUrl) {
          await appUpdate(this.boxId, data.data.updateUrl)
        }
      } catch (e) {
      }

      this.submitting = false
    },

    async getShadow () {
      const tenantId = this.userInfo.tenant_id ? this.userInfo.tenant_id : '1'
      const boxId = this.testValue === '1' ? this.boxId : tenantId + '_' + this.testValue
      const { data } = await getShadow(boxId)
      if (data) {
        // this.testResult = JSON.stringify(JSON.parse(data), null, 2)
        this.testResult = JSON.parse(data)
      }
    },

    closeLanInfo () {
      this.lanVisible = false
      this.$emit('closeLan')
    }
  }
}
</script>

<style lang="stylus" scoped>
.testArea
  border-radius 5px
  border 1px solid rgba(0,0,0,0.24)
  overflow hidden
  height 450px
  padding  20px
>>>.testArea textarea
  height 500px
  width 500px
  padding 0
  margin 20px
.flex-start
  display flex
  justify-content flex-start
  width 100%
.flex-center
  display flex
  align-items center
  justify-content center
.flex-between
  display flex
  align-items center
  justify-content space-between
.alarm-container
  display flex
  justify-content space-between
  padding 20px
  margin-bottom 20px

  .ball-container
    display flex
    align-items center
    justify-content space-around
    height 300px

  .left
    width 100%
    height 100%

    .title
      line-height 1
      font-size 16px
      font-weight 500
      color $primary
      margin-bottom 16px

  .right
    display flex
    flex-direction column
    justify-content center
    border-left 1px solid #D3D3D3

    .operator-container
      flex-direction column

    .operator
      margin-bottom 20px

    .btn
      padding: 0
      min-width 96px
      min-height 32px
      line-height 1
      width 96px
      height 32px
      border-radius 6px

    .left-btn
      margin 0 20px 0 22px

    .gateway
      width 100%
      display flex
      align-items center
      justify-content flex-end
      height 150px
      margin 20px 0 26px 0

  .living-container
    display flex
    line-height 1
    justify-content flex-end
    align-items flex-end
    width 100%

  .living
    text-align right
    margin-left 10px
    margin-right 8px
    position relative
    width 43px

    .status
      width 10px
      height 10px
      border-radius 50%
      background $positive
      position absolute
      left 0
      top 2px

    .off
      background #666666
</style>
